package com.library;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletURL;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Color;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;

import com.library.portlet.util.Constants;
import com.library.slayer.model.LMSBook;
import com.library.slayer.model.impl.LMSBookImpl;
import com.library.slayer.service.LMSBookLocalServiceUtil;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.servlet.HttpHeaders;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.PortletURLFactoryUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.liferay.util.xml.descriptor.StrictXMLDescriptor;
import com.sun.xml.internal.bind.v2.runtime.reflect.opt.Const;

/**
 * Portlet implementation class LibraryPortlet
 */
public class LibraryPortlet extends MVCPortlet {

	
	public void serveResource(ResourceRequest resourceRequest,
			ResourceResponse resourceResponse) throws IOException,
			PortletException {
		System.out.println(" inside  serveResource >>>>>>>>  ");

		try {
			String cmd = resourceRequest.getParameter("CMD");

			JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
			
				resourceResponse.setContentType("application/vnd.ms-excel");
				resourceResponse.setProperty(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=LibraryReports.xls");


			System.out.println(" inside  GenerateExcel >>>>>>>> ");

			String xlsSheetLocation = Constants.xlsSheetLocation ;
			HSSFWorkbook myWorkbook = new HSSFWorkbook();
			HSSFSheet mySheet = myWorkbook.createSheet("Library Portlet Report");

			Font font = myWorkbook.createFont();
			font.setBoldweight(Font.BOLDWEIGHT_BOLD);
			CellStyle style = myWorkbook.createCellStyle();
			style.setFont(font);
			style.setAlignment(CellStyle.ALIGN_CENTER);
			style.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());

			//   HSSFRow myRow = null;
			//  HSSFCell myCell = null;

			Row firstRow = mySheet.createRow(0);
			firstRow.createCell(0).setCellValue("Book Id");
			firstRow.createCell(1).setCellValue("Book Title");
			firstRow.createCell(2).setCellValue("Book Author");
			firstRow.createCell(3).setCellValue("Date Added");
			SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");

			int rowNum=1;
			try {
				List<LMSBook> lmsBookList = LMSBookLocalServiceUtil.getLMSBooks(0, -1);

				System.out.println("\n noOfRows  >>>>>  "+lmsBookList.size());

				for(LMSBook list : lmsBookList){
					int cellNum = 0;
					Row row = mySheet.createRow(rowNum++);
					row.createCell(cellNum++).setCellValue(String.valueOf(list.getBookId()));
					row.createCell(cellNum++).setCellValue(list.getBookTitle());
					row.createCell(cellNum++).setCellValue(list.getAuthor());
					row.createCell(cellNum++).setCellValue(String.valueOf(dateFormat.format(list.getDateAdded())));	

				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}

			//write the file object and Close..
			try{
				FileOutputStream out = new FileOutputStream(xlsSheetLocation);
				myWorkbook.write(out);
				out.close();
			}catch(Exception e){
				e.printStackTrace();
			}

		} catch (Exception e) {
			e.printStackTrace();	 
		}

	}


	public void generatePDFReport(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {

	
	
	}


	public void generateReport(ActionRequest actionRequest,ActionResponse actionResponse) throws IOException, PortletException {

		System.out.println(" inside  GenerateExcel >>>>>>>> ");

		String xlsSheetLocation = Constants.xlsSheetLocation ;
		HSSFWorkbook myWorkbook = new HSSFWorkbook();
	    HSSFSheet mySheet = myWorkbook.createSheet("Library Portlet Report");
	    
	    Font font = myWorkbook.createFont();
	    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
	    CellStyle style = myWorkbook.createCellStyle();
	    style.setFont(font);
	    style.setAlignment(CellStyle.ALIGN_CENTER);
	    style.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());
	    
	    
	 //   HSSFRow myRow = null;
	  //  HSSFCell myCell = null;
	    
	    Row firstRow = mySheet.createRow(0);
	    firstRow.createCell(0).setCellValue("Book Id");
	    firstRow.createCell(1).setCellValue("Book Title");
	    firstRow.createCell(2).setCellValue("Book Author");
	    firstRow.createCell(3).setCellValue("Date Added");
	    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
	    
		int rowNum=1;
		try {
			List<LMSBook> lmsBookList = LMSBookLocalServiceUtil.getLMSBooks(0, -1);

			System.out.println("\n noOfRows  >>>>>  "+lmsBookList.size());

			for(LMSBook list : lmsBookList){
			int cellNum = 0;
				Row row = mySheet.createRow(rowNum++);
				row.createCell(cellNum++).setCellValue(String.valueOf(list.getBookId()));
				row.createCell(cellNum++).setCellValue(list.getBookTitle());
				row.createCell(cellNum++).setCellValue(list.getAuthor());
				row.createCell(cellNum++).setCellValue(String.valueOf(dateFormat.format(list.getDateAdded())));	
				
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	 
		//write the file object and Close..
		try{
			FileOutputStream out = new FileOutputStream(xlsSheetLocation);
			myWorkbook.write(out);
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}


	public void codeReference(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {/*
		{
			String cmd = resourceRequest.getParameter(Constants.CMD);

			JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
			SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");

			PortletSession session= resourceRequest.getPortletSession();
			List<Subcription> subscription    = (List<Subcription>)session.getAttribute("resultscustomer");
			if(subscription!=null)
			{
				try
				{
					resourceResponse.setContentType("application/vnd.ms-excel");
					resourceResponse.addProperty(
							HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=Marketing.xls"
							);
					Workbook wb = new HSSFWorkbook();
					OutputStream fileOut = resourceResponse.getPortletOutputStream();
					CreationHelper createHelper = wb.getCreationHelper();
					Sheet sheet = wb.createSheet("MTS Requirement");

					CellStyle style;
					Font headerFont = wb.createFont();
					headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
					style = createBorderedStyle(wb);
					style.setAlignment(CellStyle.ALIGN_CENTER);
					style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
					style.setFillPattern(CellStyle.SOLID_FOREGROUND);
					style.setFont(headerFont);
					Row row = sheet.createRow((short)0);

					// Create a cell and put a value in it.


					// Or do it on one line.
					row.createCell(0).setCellValue("MDN");
					row.createCell(1).setCellValue("Subscription Type");
					row.createCell(2).setCellValue("Product & Pack");
					row.createCell(3).setCellValue("Circle");
					row.createCell(4).setCellValue("Subscription Status");
					row.createCell(5).setCellValue("Customer Name");
					row.createCell(6).setCellValue("Subscription Date");
					row.createCell(7).setCellValue("Renewal Date");
					row.createCell(8).setCellValue("Deactivation Date");
					row.createCell(9).setCellValue("Mobile Number");
					row.createCell(10).setCellValue("Email Address");
					int i=1;
					for(Subcription sub:subscription)
					{
						Row datarow = sheet.createRow(i);
						datarow.createCell(0).setCellValue(sub.getMdn());

						Tariff tariff = sub.getTariffId()>0?TariffLocalServiceUtil.getTariff(sub.getTariffId()):null;          	
						String subType = tariff!=null?tariff.getOption():"Trial";
						datarow.createCell(1).setCellValue(subType);

						String productpack=com.fsecure.portal.slayer.service.ProductLocalServiceUtil.getProduct(sub.getProductId()).getName()+"-"+com.fsecure.portal.slayer.service.PackLocalServiceUtil.getPack(sub.getPackageId()).getName();
						datarow.createCell(2).setCellValue(productpack);
						String status="";
						if(sub.getActive())
						{
							status="Active";
						}
						else
						{
							status="Inactive";
						}

						datarow.createCell(3).setCellValue(CustomerLocalServiceUtil.fetchByUserId(sub.getUserId()).getCircle());
						datarow.createCell(4).setCellValue(status);
						datarow.createCell(5).setCellValue(com.liferay.portal.service.UserLocalServiceUtil.getUser(sub.getUserId()).getFullName() );
						datarow.createCell(6).setCellValue(sdf.format(sub.getCrdDate()));
						datarow.createCell(7).setCellValue(sdf.format(sub.getNextCrdDate()));
						datarow.createCell(8).setCellValue(sub.getDeActivationDate()!=null?sdf.format(sub.getDeActivationDate()):"--");
						datarow.createCell(9).setCellValue(" NA ");
						DynamicQuery queryPhone = DynamicQueryFactoryUtil.forClass(Phone.class);
						queryPhone.add(RestrictionsFactoryUtil.eq("userId", sub.getUserId()));
						List<Phone> phonenumbers = PhoneLocalServiceUtil.dynamicQuery(queryPhone);
						for(Phone mobnumber : phonenumbers){
							if(mobnumber.getNumber().equalsIgnoreCase(sub.getMdn())){
								datarow.createCell(9).setCellValue(" NA ");
							}
							else {
								datarow.createCell(9).setCellValue(mobnumber.getNumber());
							}
						}

						String emailAdrs = "";
						if(sub.getIdentifier().equalsIgnoreCase("")){
							emailAdrs = "NA";
						}
						else{
							emailAdrs = com.liferay.portal.service.UserLocalServiceUtil.getUser(sub.getUserId()).getEmailAddress()!=null?com.liferay.portal.service.UserLocalServiceUtil.getUser(sub.getUserId()).getEmailAddress():" NA ";
						}
						datarow.createCell(10).setCellValue(emailAdrs);
						i++;
					}

					wb.write(fileOut);

					fileOut.close();

				}catch(Exception e)
				{
					e.printStackTrace();
				}
			}

		}

	*/}


	public void updateBook(ActionRequest actionRequest,ActionResponse actionResponse)
			throws IOException, PortletException {
			String bookTitle = ParamUtil.getString(actionRequest, "bookTitle");
			String author = ParamUtil.getString(actionRequest, "author");
			LMSBook lmsBook = null;
			long bookId = ParamUtil.getLong(actionRequest, "bookId");
		
			if (bookId > 0l) {
				try {
				lmsBook = LMSBookLocalServiceUtil.fetchLMSBook(bookId);
				} catch (SystemException e) {
				e.printStackTrace();
				}
			// set UI fields
			lmsBook.setBookTitle(bookTitle);
			lmsBook.setAuthor(author);
			lmsBook.setDateModified(new Date());
				try {
				LMSBookLocalServiceUtil.updateLMSBook(lmsBook);
				} catch (SystemException e) {
				e.printStackTrace();
				}
			} 
			else {
				// inserting the book to the database
				lmsBook = new LMSBookImpl();
				// set primary key
				try {
				bookId =CounterLocalServiceUtil.increment(
				LMSBook.class.getName());
				} catch (SystemException e) {
				e.printStackTrace();
				}
				lmsBook.setBookId(bookId);
				// set UI fields
				lmsBook.setBookTitle(bookTitle);
				lmsBook.setAuthor(author);
				// set audit field(s)
				lmsBook.setDateAdded(new Date());
				lmsBook.setDateModified(new Date());
				// insert the book using persistence api
				 
	
				try {
				LMSBookLocalServiceUtil.addLMSBook(lmsBook);
				} catch (SystemException e) {
				e.printStackTrace();
				}
			}
			// forwarding to another JSP after the book is added.
			ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
			String portletName = getPortletName() + "_WAR_" + getPortletName();
			
			PortletURL successPageURL =PortletURLFactoryUtil.create(
				actionRequest,
				portletName,
				themeDisplay.getPlid(),
				PortletRequest.RENDER_PHASE
			);
			successPageURL.setParameter("jspPage", "/html/library/list.jsp");
			actionResponse.sendRedirect(successPageURL.toString());
			}

	
	public void deleteBook(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException,
			PortletException, PortalException {

			long bookId = ParamUtil.getLong(actionRequest, "bookId");
				
			if (bookId > 0L) {
			try {
			LMSBookLocalServiceUtil.deleteLMSBook(bookId);
			} catch (PortalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			}
			}

			// redirecting to the default portlet view
			String redirectURL = ParamUtil.getString(actionRequest, "redirectURL");

			// adding custom Success messages...
			String successMessage = ParamUtil.getString(actionRequest, "successMessage");
			SessionMessages.add(actionRequest,"request_processed" ,successMessage);
			
			actionResponse.sendRedirect(redirectURL);
			}


	/*@Override
	protected void addSuccessMessage(ActionRequest actionRequest,
			ActionResponse actionResponse) {

		if(!addProcessActionSuccessMessage){
			return;
		}
		
		String successMessage = ParamUtil.getString(actionRequest, "successMessage");
		SessionMessages.add(actionRequest,"request_processed" ,successMessage);
		
		System.out.println("successMessage >>>>>>"+successMessage);
	}*/

	
}



